package spikes.button;

import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JComponent;

@SuppressWarnings("serial")
public class MezzButton extends JComponent implements MouseListener {

	private Color buttonColor = Color.GRAY;
	private String text;
	private MezzList list;
	private int collapsedInt;

	public MezzButton(String text, MezzList list) {
		this.list = list;
		this.text = text;
		
		addMouseListener(this);
	}

	public void move(int x, int y) {
		new Mover().moveTo(x, y);
	}
	
	public void expand(int width) {
		collapsedInt = getBounds().width;
		for (int i = collapsedInt; i <= width; i++) {
			Rectangle r = getBounds();
			r.width=i;
			setBounds(r);
			
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}


	}

	@Override
	public void paint(Graphics g) {
		Graphics2D g2 = (Graphics2D) g;
		
		Color beforeColor = g2.getColor();
		g2.setColor(buttonColor);
		int width = getBounds().width;
		int height = getBounds().height;
		g2.fillRect(0, 0, width-height/2, height);
		g2.fillOval(width-height, 0, height, height);
		
		
		FontMetrics fm = g2.getFontMetrics(g2.getFont());
		g2.setColor(Color.BLACK);
		g2.drawString(text, 10, height/2+fm.getHeight()/2);
		
		g2.setColor(beforeColor);
	}

	
	@Override
	public String toString() {
		return text;
	}
	
	private class Mover extends Thread {
		private int goalX, goalY;

		public void moveTo(int x, int y) {
			goalX = x;
			goalY = y;
			start();
		}

		public void run() {			
			setEnabled(false);
			Rectangle r = (Rectangle) getBounds().clone();
			while (r.x != goalX || r.y != goalY) {
				if (r.x > goalX)
					r.x--;
				if (r.x < goalX)
					r.x++;
				if (r.y > goalY)
					r.y--;
				if (r.y < goalY)
					r.y++;
				setBounds(r);
				
				try {
					Thread.sleep(20);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			setEnabled(true);
		}

	}

	@Override
	public void mouseClicked(MouseEvent arg0) {
		if (isEnabled())
			list.setToFirst(this);
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

}
